package edu.xpu.project.user.service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import edu.xpu.project.analysis.model.StudentScoreAndRank;
import edu.xpu.project.common.cache.StudentTotalScoreCache;
import edu.xpu.project.user.entity.ScoreEntity;
import edu.xpu.project.user.repository.ScoreEntityRepository;


@Service
@Transactional(readOnly=true)
public class ScoreEntityServiceImpl implements ScoreEntityService {
	@Autowired
	private ScoreEntityRepository scoreEntityRepository;

	@Override
	public ScoreEntity get(Long id) {
		return scoreEntityRepository.findOne(id);
	}

	@Transactional(readOnly=false)
	@Override
	public ScoreEntity saveOrUpdate(ScoreEntity t) {
		ScoreEntity saveAndFlush = scoreEntityRepository.saveAndFlush(t);
		return saveAndFlush;
	}

	@Transactional(readOnly=false)
	@Override
	public void delete(Long id) {
		scoreEntityRepository.delete(id);
	}

	@Override
	public Page<ScoreEntity> getPageByCriterias(String pageNumberStr, String pageSizeStr, final ScoreEntity scoreEntity) {
		Integer pageNumber = 1;
		Integer pageSize = 10;
		try {
			pageNumber = Integer.parseInt(pageNumberStr);
		} catch (Exception e) {}
		try {
			pageSize = Integer.parseInt(pageSizeStr);
		} catch (Exception e) {}
		Pageable pageable = new PageRequest(pageNumber - 1, pageSize);
		
		return scoreEntityRepository.findAll(new Specification<ScoreEntity>() {
			@Override
			public Predicate toPredicate(Root<ScoreEntity> root, CriteriaQuery<?> query,
					CriteriaBuilder builder) {
				if (scoreEntity == null) {
					return null;
				}
				//添加查询条件
				List<Predicate> predicates = new ArrayList<Predicate>(3);
				predicates.add(builder.equal(root.get("courseType").get("courseName").as(String.class), scoreEntity.getCourseType().getCourseName()));
				
				if (predicates.size() == 0) {
					return null;
				}
				Predicate[] predArr= new Predicate[predicates.size()];
				return builder.and(predicates.toArray(predArr));
			}
		}, pageable);
	}

	@Override
	public StudentScoreAndRank getStuScoreAndRankByStuId(long stuId) {
		//判断缓存中有没有数据, 如果有数据, 不需要从后台获取
		if (StudentTotalScoreCache.size() == 0) {
			//解析获取的数据
			List<Object> stuScoreAndId = scoreEntityRepository.getStuScoreAndId();
			for (int i = 0, len = stuScoreAndId.size();i < len; i++) {
				Object[] objects = (Object[]) stuScoreAndId.get(i);
				BigInteger bigStuId = (BigInteger) objects[0];
				Double bigTotalScore = (Double) objects[1];
				StudentScoreAndRank studentScoreAndRank = new StudentScoreAndRank();
				studentScoreAndRank.setStudentId(bigStuId.longValue());
				studentScoreAndRank.setStudentRank(i+1);
				studentScoreAndRank.setTotalScore(bigTotalScore);
				StudentTotalScoreCache.add(studentScoreAndRank);
			}
			
		}
		//从缓存中取数据
		return StudentTotalScoreCache.getByStuId(stuId);
	}

	@Override
	public List<ScoreEntity> findByProjectUserId(Long stuId) {
		return scoreEntityRepository.findByProjectUserId(stuId);
	}

}
